package com.fyy.socket.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

/**
 * @Author fyy
 * @Description UDP 客户端
 * @Date 2020/12/15 10:07
 */
public class AskClient {

    public static void main(String[] args) throws IOException {
        //1.创建DatagramSocket,可以指明接收数据的端口，不指明会自动分配
        DatagramSocket socket = new DatagramSocket(9000);
        //2.发送数据包
        Scanner input = new Scanner(System.in);
        while (true){
            String message = input.nextLine();
            System.out.println(message);
            byte[] buf = message.getBytes();
            int length = buf.length;
            InetAddress ip = InetAddress.getByName("127.0.0.1");
            DatagramPacket packet = new DatagramPacket(buf,length,ip,8088);
            socket.send(packet);
            if("bye".equals(message)){
                break; //客户端关闭交流
            }
            //接收服务器消息
            byte[] bufS = new byte[1024]; //接收数据包的大小
            int len = buf.length;
            DatagramPacket packetS = new DatagramPacket(bufS,len);
            socket.receive(packetS);
            String msg = new String(packetS.getData());
            System.out.println("服务器发送的数据：" + msg);
        }
        //3.关闭资源
        socket.close();
    }

}
